from marshmallow import pprint
from sqlalchemy import func
from sqlalchemy.orm import sessionmaker
from apps.users.models import UserRegister
from apps.users.serializers import UserListSerializers
from config.models import User
from config.mysql import engine
from utils.depagenation import PageNumberPagination
from utils.utils import json_response
from routers import router
from fastapi import Request


DBSession = sessionmaker(bind=engine)
db = DBSession()
PAGE_SIZE = 12


@router.post("/system/register/", tags=['users'])
async def register_user(user: UserRegister):
    try:
        _user = {"name": user.name, "age": user.age,
                 "tel": user.tel, "address": user.address}
        new_user = User(**_user)
        db.add(new_user)
        db.commit()
        db.close()
        return json_response(code=200, msg="success")
    except Exception as e:
        db.rollback()
        db.close()
        return json_response(code=400, msg="存储失败:{}".format(e))


@router.get("/system/userinfo/", tags=['users'])
async def user_info(user_id: int):
    try:
        user = db.query(User).filter(User.id==user_id).one()
        resp_data = {}
        if user:
            resp_data = {
                "name": user.name,
                "age": user.age,
                "tel": user.tel,
                "address": user.address,
                "createDate": user.createDate.strftime("%Y-%m-%d %H:%M:%S")
            }
            db.close()
        return json_response(code=200, msg="success", data=resp_data)
    except Exception as e:
        db.close()
        return json_response(code=200, msg="获取用户信息失败:{}".format(e))


@router.get("/system/all_user/", tags=['users'])
async def all_user(request: Request, page: int):
    _PAGE_SIZE = 12
    page = page if page > 0 else 1
    data = db.query(User).limit(_PAGE_SIZE).offset((page - 1) * _PAGE_SIZE)
    data = data.all()
    _ser = UserListSerializers()
    result = _ser.dump(data, many=True)
    count = len(db.query(User).all())
    page = PageNumberPagination(page_size=_PAGE_SIZE, count=count, page=page, request=request)
    return page.get_paginated_response(data=result)



